import React, { useState, useEffect } from 'react';
import { Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  fileUpload
} from "@/api/upload";
import './index.less';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default function MyUpload(props) {
  const [imageUrl, setImageUrl] = useState('')

  const beforeUpload = (file) => {
    console.log('file', file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG格式的图片!');
      return false;
    }
    const isLt2M = file.size < 512000;
    if (!isLt2M) {
      message.error('图片尺寸不得大于500k!');
      return false;
    }

    getBase64(file, imageUrl => {
      let formData = new FormData();
      formData.append("avatar", file);
      fileUpload(formData)
       .then(res => {
          if (res.data.code === 200) {
            console.log('图片上传成功', res.data.imgUrl)
            const Url = process.env.NODE_ENV === 'production' ? window.Glob.baseUrl.pro : window.Glob.baseUrl.dev
            const imgUrl = Url + res.data.imgUrl
            setImageUrl(imgUrl)
            props.getImgUrl(imgUrl);
          } else {
            setImageUrl('')
            message.error(res.data.msg);
          }
       })
       .catch(() => {
          setImageUrl('')
       })
    });
    return false;
  }

  useEffect(() => {
    setImageUrl(props.value)
  }, [imageUrl])// eslint-disable-line react-hooks/exhaustive-deps

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>点击上传</div>
    </div>
  );
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action
      beforeUpload={beforeUpload}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
  );
}